package app.project.directionlensproject.util;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class TiltDetector implements SensorEventListener {
	public static Sensor accelerometer;
	public static float[] mAccelerometer = null;
	public static float[] mGeomagnetic = null;
	public static SensorManager mSensorManager;
	public static Sensor magnetometer;
	public static float swAzimuth;
	public static float swPitch;
	public static float swRoll;

	public TiltDetector(Context paramContext) {
		mSensorManager = (SensorManager) paramContext
				.getSystemService("sensor");
		accelerometer = mSensorManager.getDefaultSensor(1);
		magnetometer = mSensorManager.getDefaultSensor(2);
		mSensorManager.registerListener(this, accelerometer, 1);
		mSensorManager.registerListener(this, magnetometer, 1);
		swRoll = 0.0F;
		swPitch = 0.0F;
		swAzimuth = 0.0F;
	}

	public void Clear() {
		mSensorManager.unregisterListener(this, accelerometer);
		mSensorManager.unregisterListener(this, magnetometer);
	}

	public void GetLatestValues(OrientationValues paramOrientationValues) {
		paramOrientationValues.Roll = swRoll;
		paramOrientationValues.Pitch = swPitch;
		paramOrientationValues.Azimuth = swAzimuth;
	}

	public void onAccuracyChanged(Sensor paramSensor, int paramInt) {
	}

	public void onSensorChanged(SensorEvent paramSensorEvent) {
		if (paramSensorEvent.sensor.getType() == 1)
			mAccelerometer = paramSensorEvent.values;
		if (paramSensorEvent.sensor.getType() == 2)
			mGeomagnetic = paramSensorEvent.values;
		if ((mAccelerometer != null) && (mGeomagnetic != null)) {
			float[] arrayOfFloat1 = new float[9];
			if (SensorManager.getRotationMatrix(arrayOfFloat1, new float[9],
					mAccelerometer, mGeomagnetic)) {
				float[] arrayOfFloat2 = new float[3];
				SensorManager.getOrientation(arrayOfFloat1, arrayOfFloat2);
				swAzimuth = (float) (180.0F * arrayOfFloat2[0] / 3.141592653589793D);
				swPitch = (float) (180.0F * arrayOfFloat2[1] / 3.141592653589793D);
				swRoll = (float) (180.0F * arrayOfFloat2[2] / 3.141592653589793D);
			}
		}
	}

	public static class OrientationValues {
		public float Azimuth;
		public float Pitch;
		public float Roll;
	}
}